package it.polimi.reTraveldream.eao;

import it.polimi.reTravelDream.dto.HotelDTO;
import it.polimi.reTravelDream.eao.HotelEAOLocal;
import it.polimi.reTraveldream.entities.Hotel;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class HotelEAO
 */
@Stateless
public class HotelEAO implements HotelEAOLocal{

   @PersistenceContext
   private EntityManager em;
   
    public HotelEAO() {
       
    }

	@Override
	public void addHotel(HotelDTO currentHotel) {
		Hotel newHotel= new Hotel(currentHotel);
		this.em.persist(newHotel);
	}

	
	@Override
	public List<HotelDTO> getAllHotel() {
		 List<Hotel> resultEntities= em.createNamedQuery(Hotel.FIND_ALL, Hotel.class)
                .getResultList();
		 List<HotelDTO> resultDTO= new ArrayList<HotelDTO>();
		 for (Hotel h: resultEntities){
			 resultDTO.add(convertToDTO(h));
		 }
		 return resultDTO;
	}
	
	 private HotelDTO convertToDTO(Hotel hotelEntity) {
			HotelDTO hotelDTO = new HotelDTO();
			hotelDTO.setId(hotelEntity.getId());
			hotelDTO.setAddress(hotelEntity.getAddress());
			hotelDTO.setDescription(hotelEntity.getDescription());
			hotelDTO.setName(hotelEntity.getName());
			hotelDTO.setStars(hotelEntity.getStars());
			hotelDTO.setCity(hotelEntity.getCity());
			hotelDTO.setPrice(hotelEntity.getPrice());
			hotelDTO.setActive(hotelEntity.isActive());
			return hotelDTO;
			
		}
	 

	@Override
	public void editHotel(HotelDTO hotelToEdit) {
		Hotel hotel= new Hotel(hotelToEdit);
		System.out.println("l'id dell'hotel is: "+hotelToEdit.getId());
		//hotel.setId(hotelToEdit.getId());
		em.merge(hotel);
	}

	@Override
	public void removeHotel(HotelDTO hotelToRemove) {
		Hotel hotel=em.find(Hotel.class, hotelToRemove.getId());
		em.remove(hotel);
	}

}
